const remote = require("@electron/remote");
const { ipcRenderer } = require("electron");
const Store = require("electron-store");
const settingsStore = new Store({ name: "Settings" });
const qiniuConfigArr = ["#savedFileLocation", "#accessKey", "#secretKey", "#bucketName"];

const $ = (selector) => {
    const result = document.querySelectorAll(selector);
    return result.length > 1 ? result : result[0];
};

// 监听仅html dom加载完成时
document.addEventListener("DOMContentLoaded", () => {
    let savedLocation = settingsStore.get("savedFileLocation") || "";
    // 取缓存。如果之前已经存储过路径，就取出，赋到input上
    if (savedLocation) {
        $("#savedFileLocation").value = savedLocation;
    }

    // 从缓存取 savedFileLocation accessKey secretKey bucketName
    qiniuConfigArr.forEach((selector) => {
        // 存入的时候键名前面没有#，所以要去除#再获取
        const savedValue = settingsStore.get(selector.substring(1));
        if (savedValue) {
            // 赋到节点上
            $(selector).value = savedValue;
        }
    });

    $("#select-new-location").addEventListener("click", () => {
        remote.dialog
            .showOpenDialog({
                // 打开选择文件夹的弹窗
                properties: ["openDirectory"],
                message: "选择文件的存储路径",
            })
            .then((path) => {
                if (Array.isArray(path.filePaths)) {
                    // 把获取到的路径，赋值到input上
                    $("#savedFileLocation").value = path.filePaths[0];
                }
            });
    });
    $("#settings-form").addEventListener("submit", (e) => {
        e.preventDefault();
        qiniuConfigArr.forEach((selector) => {
            if ($(selector)) {
                // 从节点上取出id（不带#）和value
                const { id, value } = $(selector);
                settingsStore.set(id, value ? value : "");
            }
        });

        // 更改七牛云配置后，发送事件到main.js，云同步菜单配置更新
        ipcRenderer.send("config-is-saved");
        // 这里有个bug，选择其他文件夹后，再保存，会把父窗口一起关闭
        remote.getCurrentWindow().close();
    });

    $(".nav-tabs").addEventListener("click", (e) => {
        e.preventDefault();
        $(".nav-link").forEach((element) => {
            element.classList.remove("active");
        });
        e.target.classList.add("active");
        $(".config-area").forEach((element) => {
            element.style.display = "none";
        });
        $(e.target.dataset.tab).style.display = "block";
    });
});
